<?php


namespace app\admin\controller\conf;

use app\admin\model\ConfArea;
use app\admin\traits\Curd;
use app\common\controller\AdminController;
use think\App;
use EasyAdmin\annotation\NodeAnotation;
use EasyAdmin\annotation\ControllerAnnotation;
use think\facade\Db;
use think\Model;

/**
 * Class Goods
 * @package app\admin\controller\conf
 * @ControllerAnnotation(title="县市管理")
 */
class Area extends AdminController
{

    use Curd;

    protected $relationSearch = false;
    protected $level=['县（市）级','乡镇级','村（社区）级'];

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = new ConfArea();
    }

    /**
     * @NodeAnotation(title="县市列表")
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            list($page, $limit, $where) = $this->buildTableParames();
            $count = $this->model->where($where)->count();
            $list = $this->model->where($where)->page($page, $limit)->order($this->sort)->select();
            foreach ($list as $k=>$v){
                $list[$k]=$this->resetInfo($v);
            }
            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="添加县市")
     */
    public function add($id = null)
    {
        if ($this->request->isAjax()) {
            $post = $this->request->post();
            $rule = [
                'name|名称'   => 'require',
            ];
            $this->validate($post, $rule);
            $post['level']=$this->getLevel($post['pid']);
            try {
                $save = $this->model->save($post);
                $this->updateAreaFile();
            } catch (\Exception $e) {
                $this->error('保存失败');
            }
            if ($save) {
                $this->success('保存成功');
            } else {
                $this->error('保存失败');
            }
        }else{
            $area=$this->getSelectList();
            $this->assign([
                'area'=>$area,
            ]);
        }
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="编辑县市")
     */
    public function edit($id)
    {
        $row = $this->model->find($id);
        empty($row) && $this->error('数据不存在');
        if ($this->request->isAjax()) {
            $post = $this->request->post();
            $rule = [
                'name|名称'   => 'require',
            ];
            $this->validate($post, $rule);
            $post['level']=$this->getLevel($post['pid']);
            try {
                $save = $row->save($post);
                $this->updateAreaFile();
            } catch (\Exception $e) {
                $this->error('保存失败');
            }
            if ($save) {
                $this->success('保存成功');
            } else {
                $this->error('保存失败');
            }
        }else{
            $area=$this->getSelectList();
            $this->assign([
                'id'          => $id,
                'row'         => $row,
                'area'=>$area,
            ]);
        }
        return $this->fetch();
    }
    /**
     * @NodeAnotation(title="删除县市")
     */
    public function delete($id)
    {
        $row = $this->model->whereIn('id', $id)->select();
        $row->isEmpty() && $this->error('数据不存在');
        if($this->model->where(['pid'=>$id])->count()>0)$this->error('请先删除子级！');
        $self=$row->toArray()[0];
        try {
            $save =$row->delete();
            $this->updateAreaFile();
        } catch (\Exception $e) {
            $this->error('删除失败');
        }
        $save ? $this->success('删除成功') : $this->error('删除失败');
    }

    private function getLevel($pid){
        $level=1;
        if(!empty($pid)){
            $parent=$this->model->where(['id'=>$pid])->field('level')->find();
            if($parent){
                $level=$parent['level']+1;
            }
        }
        return $level;
    }
    private function resetInfo($info){
        $info['pid_text']='顶级';
        if(!empty($info['pid'])){
            $parent=$this->model->where(['id'=>$info['pid']])->field('name')->find();
            $info['pid_text']='';
            if($parent){
                $info['pid_text']=$parent['name'];
            }
        }
        $info['level_text']='';
        if(!empty($info['level'])){
            $info['level_text']=$this->level[$info['level']-1];
        }
        return $info;
    }

    private function getSelectList(){
        $returnData=[];
        $firstData=$this->model->where(['level'=>1])->order('order asc')->select();
        if(count($firstData)>0){
            $firstData=$firstData->toArray();
            foreach ($firstData as $k=>$v){
                $areaM=new ConfArea();
                $returnData[$v['id']]=$v;
                $child=$areaM->where(['pid'=>$v['id']])->order('order asc')->select();
                $returnData[$v['id']]['child']=[];
                if(count($child)>0){
                    $child=$child->toArray();
                    foreach ($child as $k1=>$v1){
                        $areaM=new ConfArea();
                        $returnData[$v['id']]['child'][$v1['id']]=$v1;
                        $child2=$areaM->where(['pid'=>$v1['id']])->order('order asc')->select();
                        $returnData[$v['id']]['child'][$v1['id']]['child']=[];
                        if(count($child2)>0){
                            $child2=$child2->toArray();
                            foreach ($child2 as $k2=>$v2){
                                $returnData[$v['id']]['child'][$v1['id']]['child'][$v2['id']]=$v2;
                            }
                        }
                    }
                }
            }
        }
        return $returnData;
    }

    private function updateAreaFile(){

        $data=$this->getSelectList();
        foreach ($data as $k=>$v){
            $v['count']=0;
            foreach ($v['child'] as $k1=>$v1){
                $v1['count']=0;
                foreach ($v1['child'] as $k2=>$v2){
                    $v1['count']+=$v2['count'];
                }
                $v['child'][$k1]=$v1;
                $v['count']+=$v1['count'];
                $update1['count']=$v1['count'];
                Db::table('ea_conf_area')->where(['id'=>$v1['id']])->update($update1);
            }
            $data[$k]=$v;
            $update['count']=$v['count'];
            Db::table('ea_conf_area')->where(['id'=>$v['id']])->update($update);
        }
        $this->setFile('../config/areaCache.php',$data);
    }
}